package com.zz.common.zid

import java.time.Instant

import cats.data.OptionT
import cats.effect.IO
import com.zz.common.service.IdService.Zid
import scala.collection.mutable

import com.zz.ady.idl.IdType
import com.zz.idl.{IdBundle, IdBundleMeta, ReversedIndexMeta}

/**
  * FOR TEST ONLY!!!
  */
class InMememoryZidStorage extends ZidStorage [IO]{
  val index = mutable.Map[String, (IdBundle, IdBundleMeta)]()
  val reverseIndex = mutable.Map[String, (String, Set[String], ReversedIndexMeta)]()

  override def storeIdBundle(idBundle: IdBundle, idBundleMeta: IdBundleMeta): IO[Unit] = IO{
    index.put(idBundle.zid, (idBundle, idBundleMeta))
  }

  override def storeReversedIndex(id: String, idType: IdType, zid: String, reversedIndexMeta: ReversedIndexMeta): IO[Unit] = IO{
    reverseIndex.get(idType.toString()+id) match {
      case Some(zid_zids_meta)=>
        val newZid = zid
        val newZids = zid_zids_meta._2 + zid
        val newMeta = ReversedIndexMeta(Instant.now.toEpochMilli)
        reverseIndex.put(idType.toString()+id, (newZid, newZids, newMeta))
      case None =>
        val newZid = zid
        val newZids = Set(zid)
        val newMeta = ReversedIndexMeta(Instant.now.toEpochMilli)
        reverseIndex.put(idType.toString()+id, (newZid, newZids, newMeta))
    }
  }

  override def queryZidInfo(zid: String): OptionT[IO, (IdBundle, IdBundleMeta)] = OptionT(IO(
    index.get(zid)
  ))

  override def queryZids(id: String, idType: IdType): OptionT[IO, (Zid, Seq[Zid], ReversedIndexMeta)] = OptionT(IO{
    val result = reverseIndex.get(idType.toString() + id)
    result.map{
      case (zid, zidSet, riMeta) =>
        (zid, zidSet.toSeq, riMeta)
    }
  })
}
